package api

import (
	"api/app/auth/auto/v1/mc"
	"api/app/auth/models"
	"api/config/code"
	"api/libs/api"
	"api/libs/errs"
	"api/libs/orm"
	"fmt"
	"gitee.com/dreamwood/ez"
	"gitee.com/dreamwood/ez/server"
)

type ModelApi struct {
	api.BaseApi
	HttpQuery *orm.HttpQuery
}

func (c *ModelApi) Prepare() {
	c.RoutePrefix = fmt.Sprintf("/auth/admin/%s", "Model")
	// 必要步骤
	c.SetBefore(func(operation *server.Operation) {
		// 前置操作
	})
}

func (c *ModelApi) SaveAction(operation *server.Operation) {
	this := c.TakeOver(operation).GetHttpQuery()
	model := new(models.Model)
	factory := orm.NewFactory(mc.ModelEzConfig, true)
	factory.SetCtx(operation.CreateContext())
	if this.Try(this.FillJson(model)) {
		return
	}
	if model.Id == 0 {
		factory.TriggerNew(model)
	}
	if this.Try(factory.Update(model)) {
		return
	}
	if this.Try(factory.Find(model, model.Id)) {
		return
	}
	if this.Try(factory.FillM2M(model)) {
		return
	}
	this.ReturnSuccess("保存成功", model)
}

func (c *ModelApi) GetAction(operation *server.Operation) {
	this := c.TakeOver(operation).GetHttpQuery()
	id := this.Get(`id`).IsInt()
	model := new(models.Model)
	factory := orm.NewFactory(mc.ModelEzConfig)
	factory.SetCtx(operation.CreateContext())
	if this.Try(factory.Find(model, id)) {
		return
	}
	if this.Try(factory.FillM2MId(model)) {
		return
	}
	this.ReturnSuccess("OK", model)
}

func (c *ModelApi) ScanAction(operation *server.Operation) {
	this := c.TakeOver(operation).GetHttpQuery()
	id := this.Get(`id`).IsInt()
	model := new(models.Model)
	factory := orm.NewFactory(mc.ModelEzConfig)
	if this.Try(factory.Find(model, id)) {
		return
	}
	orm.Scan(model, this.HttpQuery.GetGroup(), this.HttpQuery.Depth)
	this.ReturnSuccess("OK", model)
}
func (c *ModelApi) ListAction(operation *server.Operation) {
	this := c.TakeOver(operation).GetHttpQuery()
	list := make([]*models.Model, 0)
	factory := orm.NewFactory(mc.ModelEzConfig)
	e := factory.FindBy(&list, this.HttpQuery.Conditions, this.HttpQuery.Order, this.HttpQuery.Page, this.HttpQuery.Limit)
	if this.Try(e) {
		return
	}
	count, e := factory.Count(this.HttpQuery.Conditions)
	if this.Try(e) {
		return
	}
	for _, md := range list {
		orm.Scan(md, this.HttpQuery.GetGroup(), this.HttpQuery.Depth)
	}
	outPut := server.NewJsonOut(code.Success, "列表获取成功", ez.M{
		"lists": list,
		"query": ez.M{"page": this.HttpQuery.Page, "limit": this.HttpQuery.Limit, "total": count},
	})
	this.JsonOut(outPut)
}

func (c *ModelApi) DeleteAction(operation *server.Operation) {
	this := c.TakeOver(operation).GetHttpQuery()
	id := operation.Get(`id`).IsInt()
	factory := orm.NewFactory(mc.ModelEzConfig, true)
	model := &models.Model{Id: id}
	if this.Try(factory.Delete(model)) {
		return
	}
	this.ReturnSuccess("删除成功", "")
}
func (c *ModelApi) ChoiceAction(operation *server.Operation) {
	this := c.TakeOver(operation).GetHttpQuery()
	list := make([]*models.Model, 0)
	factory := orm.NewFactory(mc.ModelEzConfig)
	e := factory.FindBy(&list, this.HttpQuery.Conditions, this.HttpQuery.Order, this.HttpQuery.Page, this.HttpQuery.Limit)
	if this.Try(e) {
		return
	}
	count, e := factory.Count(this.HttpQuery.Conditions)
	if this.Try(e) {
		return
	}
	choices := make([]ez.M, 0)
	for _, md := range list {
		choices = append(choices, md.MakeChoice())
	}
	outPut := server.NewJsonOut(code.Success, "列表获取成功", ez.M{
		"lists": choices,
		"query": ez.M{"page": this.HttpQuery.Page, "limit": this.HttpQuery.Limit, "total": count},
	})
	this.JsonOut(outPut)
}
func (c *ModelApi) CopyAction(op *server.Operation) {
	this := c.TakeOver(op)
	ids := ez.NewIds()
	if this.Try(this.FillJson(ids)) {
		return
	}
	crud := models.NewModelCrud()
	count := 0
	for _, id := range ids.Ids {
		find, e := crud.Find(id)
		if this.Try(e) {
			continue
		}
		find.Id = 0
		find.Save(true)
		count++
	}
	this.ReturnSuccess(fmt.Sprintf("成功复制%d条记录。", count), "")
}

func (c *ModelApi) DeleteManyAction(op *server.Operation) {
	this := c.TakeOver(op)
	ids := ez.NewIds()
	if this.Try(this.FillJson(ids)) {
		return
	}
	crud := models.NewModelCrud()
	crud.Factory.SetEventOn()
	count := 0
	for _, id := range ids.Ids {
		find, e := crud.Find(id)
		if this.Try(e) {
			return
		}
		e = crud.Factory.Delete(find)
		if this.Try(e) {
			return
		}
		count++
	}
	this.ReturnSuccess(fmt.Sprintf("成功删除%d条记录。", count), "")
}

func (c *ModelApi) SaveManyAction(operation *server.Operation) {
	this := c.TakeOver(operation)
	query := struct {
		Ids   []int                  `json:"ids"`
		Model map[string]interface{} `json:"_action"`
	}{}
	e := operation.FillJson(&query)
	if this.Try(e) {
		return
	}
	crud := models.NewModelCrud()
	fields := make([]string, 0)
	for field, _ := range query.Model {
		fields = append(fields, field)
	}
	f := crud.Factory
	f.Selects = fields
	for _, id := range query.Ids {
		toUpdate := new(models.Model)
		err := f.CreateFromObject(query.Model, toUpdate)
		if errs.Try(err) {
			continue
		}
		toUpdate.Id = id
		// 因为一些原因，批量修改不应该触发修改事件
		err = f.Update(toUpdate)
		if errs.Try(err) {
			continue
		}
	}
	this.ReturnSuccess("OK", "")
}
